package us.team.openAnAppAtRandom;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

public class FloatingWindowService extends Service {
    private WindowManager windowManager;
    private View floatingView;
    private View controlPanelView;
    private View floatingButton;
    private WindowManager.LayoutParams floatingParams;
    private WindowManager.LayoutParams panelParams;
    private boolean isPanelVisible = false;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        createFloatingWindow();
        createControlPanel();
    }

    private void createFloatingWindow() {
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        
        floatingView = LayoutInflater.from(this).inflate(R.layout.floating_window, null);
        
        int layoutFlag;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutFlag = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutFlag = WindowManager.LayoutParams.TYPE_PHONE;
        }

        floatingParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                layoutFlag,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        floatingParams.gravity = Gravity.TOP | Gravity.END;
        floatingParams.x = 100;
        floatingParams.y = 100;
        
        windowManager.addView(floatingView, floatingParams);
        setupTouchListener();
    }

    private void createControlPanel() {
        controlPanelView = LayoutInflater.from(this).inflate(R.layout.control_panel, null);
        
        int layoutFlag;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutFlag = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutFlag = WindowManager.LayoutParams.TYPE_PHONE;
        }

        panelParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                layoutFlag,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        panelParams.gravity = Gravity.CENTER;
        
        setupPanelListeners();
    }

    private void setupTouchListener() {
        floatingButton = floatingView.findViewById(R.id.floating_button);
        
        floatingButton.setOnTouchListener(new View.OnTouchListener() {
            private int initialX, initialY;
            private float initialTouchX, initialTouchY;
            private boolean isClick = true;
            private long touchStartTime;

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        initialX = floatingParams.x;
                        initialY = floatingParams.y;
                        initialTouchX = event.getRawX();
                        initialTouchY = event.getRawY();
                        isClick = true;
                        touchStartTime = System.currentTimeMillis();
                        return true;

                    case MotionEvent.ACTION_MOVE:
                        // 由于使用了Gravity.END，x坐标需要反向计算
                        floatingParams.x = initialX - (int) (event.getRawX() - initialTouchX);
                        floatingParams.y = initialY + (int) (event.getRawY() - initialTouchY);
                        windowManager.updateViewLayout(floatingView, floatingParams);
                        
                        if (Math.abs(event.getRawX() - initialTouchX) > 10 || 
                            Math.abs(event.getRawY() - initialTouchY) > 10) {
                            isClick = false;
                        }
                        return true;

                    case MotionEvent.ACTION_UP:
                        if (isClick && (System.currentTimeMillis() - touchStartTime) < 200) {
                            toggleControlPanel();
                        }
                        return true;
                }
                return false;
            }
        });
    }

    private void toggleControlPanel() {
        if (isPanelVisible) {
            hideControlPanel();
        } else {
            showControlPanel();
        }
    }

    private void showControlPanel() {
        if (!isPanelVisible) {
            windowManager.addView(controlPanelView, panelParams);
            isPanelVisible = true;
        }
    }

    private void hideControlPanel() {
        if (isPanelVisible) {
            windowManager.removeView(controlPanelView);
            isPanelVisible = false;
        }
    }

    private void setupPanelListeners() {
        // 录屏按钮
        Button btnScreenRecord = controlPanelView.findViewById(R.id.btn_screen_record);
        btnScreenRecord.setOnClickListener(v -> {
            startScreenRecord();
            hideControlPanel();
        });

        // 控制中心按钮（不可实现）
        Button btnControlCenter = controlPanelView.findViewById(R.id.btn_control_center);
        btnControlCenter.setOnClickListener(v -> {
            Toast.makeText(this, "Android无法直接调用系统下拉控制中心", Toast.LENGTH_LONG).show();
            hideControlPanel();
        });

        // 功能3按钮
        Button btnFunction3 = controlPanelView.findViewById(R.id.btn_function3);
        btnFunction3.setOnClickListener(v -> {
            Toast.makeText(this, "功能3被点击", Toast.LENGTH_SHORT).show();
            hideControlPanel();
        });

        // 功能4按钮
        Button btnFunction4 = controlPanelView.findViewById(R.id.btn_function4);
        btnFunction4.setOnClickListener(v -> {
            Toast.makeText(this, "功能4被点击", Toast.LENGTH_SHORT).show();
            hideControlPanel();
        });
    }

    private void startScreenRecord() {
        try {
            Intent intent = new Intent(this, ScreenRecordActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            Toast.makeText(this, "启动录屏", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "启动录屏失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (floatingView != null) {
            windowManager.removeView(floatingView);
        }
        if (isPanelVisible && controlPanelView != null) {
            windowManager.removeView(controlPanelView);
        }
    }
}